<template>
	<div class="overflow-hidden">
		<n-card :bordered="false" class="h-full rounded-8px shadow-sm">
			<div class="flex-col h-full">

				<div class=" w-full  ">
					<n-space class="pb-12px flex-items-center" justify="space-between">
						<n-space class="flex-items-center">
							<n-button type="primary" @click="handleAddTable">
								<icon-ic-round-plus class="mr-4px text-20px" />
								新增
							</n-button>
						</n-space>
						<n-space align="center" :size="18">
							<n-button size="small" type="primary" @click="getTableData">
								<icon-mdi-refresh class="mr-4px text-16px" :class="{ 'animate-spin': loading }" />
								刷新表格
							</n-button>
							<column-setting v-model:columns="columns" />
						</n-space>
					</n-space>
				</div>
				<div class="h-full  flex">
					<n-data-table :columns="columns" :data="tableData" :loading="loading" :pagination="pagination" size="small"
						:single-line="false" flex-height class="flex-1" />
					<table-action-modal v-model:visible="visible" :type="modalType" :edit-data="editData"
						@on-confirm="() => { getTableData(); }" />
				</div>
			</div>
		</n-card>
	</div>
</template>

<script setup lang="tsx">
import { reactive, ref } from "vue";
import type { Ref } from "vue";
import { NButton, NSpace, NPopconfirm, NTag } from "naive-ui";
import type { DataTableColumns, PaginationProps } from "naive-ui";
import { GetJobTaskList, triggerJob, delJob, stopJob } from "@/service";
import { useBoolean, useLoading } from "@/hooks";
import ColumnSetting from "../../component/table/column-setting.vue";
import TableActionModal from "./components/table-action.vue";
import type { ModalType } from "./components/table-action.vue";
import { JobStatusEnumStr, JobTypeStr, TimingTypeEnumStr, JobStatusEnum, JobType, TimingTypeEnum } from "~/src/typings/types";

const { loading, startLoading, endLoading } = useLoading(false);
const { bool: visible, setTrue: openModal } = useBoolean();

const tableData = ref<TaskCenter.GetJobTaskListOutput[]>([]);

function setTableData(data: TaskCenter.GetJobTaskListOutput[]) {
	tableData.value = data;
}
async function getTableData() {
	startLoading();
	const { data } = await GetJobTaskList();
	if (data) {
		pagination.itemCount = data.length;
		setTableData(data);
		endLoading();
	}
}

const columns: Ref<DataTableColumns<TaskCenter.GetJobTaskListOutput>> = ref([
	{
		type: "selection",
		align: "center",
	},
	{
		key: "index",
		title: "序号",
		align: "center",
		width: 80,
		render: (_, index) => {
			return `${index + 1}`
		}
	},
	{
		title: '名称',
		key: 'name',
		align: 'center'
	},
	{
		title: '绑定用户',
		key: 'userName',
		align: 'center'
	},
	{
		title: '任务状态',
		key: 'jobStatus',
		align: 'center',
		render: (row) => {
			let tagType: NaiveUI.ThemeColor = "error";
			switch (row.jobStatus) {
				case JobStatusEnum.Run:
					tagType = "success";
					break;
				case JobStatusEnum.Stop:
					tagType = "error";
					break;
			}
			return (
				<NTag type={tagType}>
					{JobStatusEnumStr[row.jobStatus as JobStatusEnum]}
				</NTag>
			);
		}
	},
	{
		title: '任务类型',
		key: 'jobTaskType',
		align: 'center',
		render: (row) => {
			return JobTypeStr[row.jobTaskType as JobType];
		}
	},
	// {
	// 	title: '创建时间',
	// 	key: 'createTime',
	// 	align: 'center',
	// 	//	render: (row) => row.createTime
	// },
	// {
	// 	title: '最后修改时间',
	// 	key: 'lastModifiedTime',
	// 	align: 'center',
	// 	//	render: (row) => row.lastModifiedTime
	// },
	// {
	// 	title: '任务所需要的数据',
	// 	key: 'jobTaskData',
	// 	align: 'center'
	// },
	{
		title: '定时类型',
		key: 'timingType',
		align: 'center',
		render: (row) => {
			return TimingTypeEnumStr[row.timingType as TimingTypeEnum];
		}
	},
	{
		title: '间隔时间（秒）',
		key: 'intervalSeconds',
		align: 'center'
	},
	{
		title: '重复次数',
		key: 'repeat',
		align: 'center'
	},
	{
		title: 'cron表达式',
		key: 'cronExpression',
		align: 'center'
	},
	{
		title: '最后执行时间',
		key: 'lastExecutionTime',
		align: 'center',
		//render: (row) => row.lastExecutionTime
	},
	{
		title: '下次执行时间',
		key: 'nextExecutionTime',
		align: 'center',
		//render: (row) => row.nextExecutionTime ? new Date(row.nextExecutionTime).toLocaleString() : ''
	},
	{
		key: "actions",
		title: "操作",
		align: "center",
		render: (row) => {
			return (
				<NSpace justify={"center"}>
					<NButton size={"small"} onClick={() => handleLookTable(row.id)}>
						详情
					</NButton>
					<NButton size={"small"} onClick={() => handleEditTable(row.id)}>
						编辑
					</NButton>
					<NButton size={"small"} onClick={() => TriggerJob(row.id)}>
						手动执行
					</NButton>
					<NPopconfirm onPositiveClick={() => handleStopJob(row.id)}>
						{{
							default: () => "确认停止",
							trigger: () => <NButton size={"small"}>停止</NButton>,
						}}
					</NPopconfirm>
					<NPopconfirm onPositiveClick={() => handleDeleteTable(row.id)}>
						{{
							default: () => "确认删除",
							trigger: () => <NButton size={"small"}>删除</NButton>,
						}}
					</NPopconfirm>
				</NSpace>
			);
		},
	}
]) as Ref<DataTableColumns<TaskCenter.GetJobTaskListOutput>>;


const editData = ref<TaskCenter.GetJobTaskListOutput | null>(null);
function setEditData(data: TaskCenter.GetJobTaskListOutput | null) {
	editData.value = data;
}
const modalType = ref<ModalType>("look");

function setModalType(type: ModalType) {
	modalType.value = type;
}

/**
 * 查看详情
 * @param rowId
 */
function handleLookTable(rowId: number) {
	const findItem = tableData.value.find((item) => item.id === rowId);
	if (findItem) {
		setEditData(findItem);
	}
	setModalType("look");
	openModal();
}

/**
 * 手动触发任务
 * @param rowId
 */
async function TriggerJob(rowId: number) {
	const findItem = tableData.value.find((item) => item.id === rowId);
	console.log(findItem);
	if (findItem) {
		triggerJob(findItem.jobId);
		await getTableData();
	}
}


/**
 * 新增
 */
function handleAddTable() {
	setModalType("add");
	setEditData(null);
	openModal();
}



/**
 * 暂停
 */
async function handleStopJob(rowId: number) {
	await stopJob(rowId);
	window.$message?.success(`停止成功`);
	await getTableData();
}
/**
 * 删除
 */
async function handleDeleteTable(rowId: number) {
	await delJob(rowId);
	window.$message?.success(`删除成功`);
	await getTableData();
}
/**
 * 编辑
 * @param rowId
 */
function handleEditTable(rowId: number) {
	const findItem = tableData.value.find((item) => item.id === rowId);
	if (findItem) {
		setEditData(findItem);
	}
	setModalType("edit");
	openModal();
}

const pagination: PaginationProps = reactive({
	page: 1,
	pageSize: 20,
	showSizePicker: true,
	pageSizes: [20, 30, 50, 100],
	prefix: (pagingInfo) => `共 ${pagingInfo.itemCount} 条`,
	onChange: (page: number) => {
		pagination.page = page;
	},
	onUpdatePageSize: (pageSize: number) => {
		pagination.pageSize = pageSize;
		pagination.page = 1;
	},
});

function init() {
	getTableData();
}

// 初始化
init();
</script>

<style scoped></style>
